package com.purchasing.system.service;

import com.purchasing.system.model.Permission;
import com.purchasing.system.model.Role;
import com.purchasing.system.model.User;
import com.purchasing.system.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PermissionService {

    private final RoleRepository roleRepository;

    @Autowired
    public PermissionService(RoleRepository roleRepository) {
        this.roleRepository = roleRepository;
    }

    /**
     * 检查用户是否拥有指定权限
     */
    public boolean hasPermission(User user, String requiredPermission) {
        Set<Permission> userPermissions = user.getRoles().stream()
                .flatMap(role -> role.getPermissions().stream())
                .collect(Collectors.toSet());

        return userPermissions.stream()
                .anyMatch(perm -> perm.getName().equals(requiredPermission));
    }

    /**
     * 获取用户所有权限名称
     */
    public Set<String> getUserPermissions(User user) {
        return user.getRoles().stream()
                .flatMap(role -> role.getPermissions().stream())
                .map(Permission::getName)
                .collect(Collectors.toSet());
    }
}